package com.lyx.user.controller;

import com.google.gson.Gson;
import com.lyx.common.constant.RedisContant;
import com.lyx.common.exception.BusinessException;
import com.lyx.common.exception.ExceptionEnum;
import com.lyx.common.result.R;
import com.lyx.common.result.Result;
import com.lyx.common.result.ResultUtil;
import com.lyx.common.utils.JwtUtils;
import com.lyx.user.dto.WxLoginDto;
import com.lyx.user.entity.User;
import com.lyx.user.service.UserService;
import com.lyx.user.utils.ConstantWxUtils;
import com.lyx.user.utils.HttpClientUtils;
import com.lyx.user.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * 微信登录
 * @author 14667
 * @date 2022/7/19 13:43
 */
@Controller
@CrossOrigin
@RequestMapping("/wechat")
public class WechatController {
    @Autowired
    public UserService userService;

    @Autowired
    public StringRedisTemplate redisTemplate;

//    @GetMapping("login")
//    public String getWxCode(){
//        //固定地址，后面拼接参数
////        String url = "https://open.weixin.qq.com/" +
////                "connect/qrconnect?appid="+ ConstantWxUtils.WX_OPEN_APP_ID+"&response_type=code";
//        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
//                "?appid=%s" +
//                "&redirect_uri=%s" +
//                "&response_type=code" +
//                "&scope=snsapi_login" +
//                "&state=%s" +
//                "#wechat_redirect";
//        //对redirect_uri进行编码
//        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
//        try {
//            String encode = URLEncoder.encode(redirectUrl,"utf-8");
//        } catch (UnsupportedEncodingException e) {
//            throw new BusinessException(ExceptionEnum.ENCODE_UNSUPPORT);
//        }
//        String url = String.format(baseUrl,ConstantWxUtils.WX_OPEN_APP_ID,redirectUrl,"com.atguigu");
//        return "redirect:"+url;
//    }

    /**
     * 微信登录
     * @param code
     * @return
     */
    //2 获取扫描人信息，添加数据
    @GetMapping("callback")
    @ResponseBody
    public R callback(String code) {
        WxLoginDto wxLoginDto = userService.wxlogin(code);
        return R.ok().data("data",wxLoginDto).message("微信验证成功");
    }

    /**
     * 绑定手机号
     * @param userVo
     * @return
     */
    @PostMapping("/binding")
    @ResponseBody
    public R binding(@RequestBody UserVo userVo){
        WxLoginDto wxLoginDto = userService.add(userVo);
        return R.ok().data("data",wxLoginDto).message("绑定手机号成功");
    }

}
